import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

// if (image != null) {
//   white.color=Colors.white;
//   white.colorFilter=ui.ColorFilter.mode(Colors.white, ui.BlendMode.srcIn);//fixme 修改图片的颜色
//   c.drawImage(image!, Offset(0, 0), white);
// }
class CanvasUtils {
  //static Paint white = BasicPalette.white.paint();
  // String path="https://img2.baidu.com/it/u=3764578826,622541035&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=711";
  // CanvasUtils.getNetImage(path,
  //     width: 100)
  //     ?.then((value) {
  //   image = value;
  // });
  // if (image != null) {
  //   canvas.drawImage(image!, Offset(width / 2, height / 2), white);
  // }
  //方法1：获取网络图片 返回ui.Image
  static Future<ui.Image> getNetImage(String url,
      {int? width = null, int? height = null}) async {
    ByteData data = await NetworkAssetBundle(Uri.parse(url)).load(url);
    ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List(),
        targetWidth: width, targetHeight: height);
    ui.FrameInfo fi = await codec.getNextFrame();
    return fi.image;
  }

  // //方法2.1：获取本地图片  返回ui.Image 需要传入BuildContext context
  // static Future<ui.Image> getAssetImage2(String asset,BuildContext context,{width,height}) async {
  //   ByteData data = await DefaultAssetBundle.of(context).load(asset);
  //   ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List(),targetWidth: width,targetHeight: height);
  //   ui.FrameInfo fi = await codec.getNextFrame();
  //   return fi.image;
  // }

  //static Paint white = BasicPalette.white.paint();
  // String path=getPackagesImagesPath("expression/cry.png");
  // CanvasUtils.getAssetImage(path,
  //         width: 100)
  //     ?.then((value) {
  //   image = value;
  // });
  // if (image != null) {
  //   canvas.drawImage(image!, Offset(width / 2, height / 2), white);
  // }
  //方法2.2：获取本地图片 返回ui.Image 不需要传入BuildContext context
  ///fixme 只能获取本地工程目录，Assets下的图片；android本地File文件无法通过此方法获取。亲测！
  static Future<ui.Image> getAssetImage(String asset,
      {int? width = null, int? height = null}) async {
    ByteData data = await rootBundle.load(asset);
    ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List(),
        targetWidth: width, targetHeight: height);
    ui.FrameInfo fi = await codec.getNextFrame();
    return fi.image;
  }

  ///获取本地文件图片;亲测可行。
  static Future<ui.Image> getFileImage(String path,
      {int? width = null, int? height = null}) async {
    File file = File(path);
    var data = await file.readAsBytes();
    ui.Codec codec = await ui.instantiateImageCodec(data,
        targetWidth: width, targetHeight: height);
    ui.FrameInfo fi = await codec.getNextFrame();
    return fi.image;
  }
}
